import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, StyleSheet, ScrollView, Platform, Alert, Image, TextInput } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useRouter, useLocalSearchParams } from 'expo-router';
import * as ImagePicker from 'expo-image-picker';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import { theme } from '../../theme';




type FormRule = {
  required?: boolean;
  message?: string;
  validator?: (value: any) => boolean | string;
};

type FormField = {
  name: string;
  label: string;
  type: 'text' | 'number' | 'select' | 'textarea' | 'phone' | 'image' | 'datetime' | 'location';
  placeholder?: string;
  rules?: FormRule[];
  options?: { label: string; value: string }[];
  width?: 'full' | 'half';
  dateFormat?: string;
};

type FormProps = {
  fields: FormField[];
  initialValues?: Record<string, any>;
  onSubmit: (values: Record<string, any>) => void;
  submitText?: string;
  images?: string[];
  onImagesChange?: (images: string[]) => void;
};

export default function Form({ fields, initialValues = {}, onSubmit, submitText = '提交', images = [], onImagesChange }: FormProps) {
  const [formData, setFormData] = React.useState(initialValues);
  const [errors, setErrors] = React.useState<Record<string, string>>({});
  const [localImages, setLocalImages] = useState<string[]>(images);
  const [dateTimePickerField, setDateTimePickerField] = useState<string | null>(null);
  const [isDatePickerVisible, setDatePickerVisible] = useState(false);
  const router = useRouter();
  const params = useLocalSearchParams();

  // 监听路由参数变化，更新表单数据
  useEffect(() => {
    const newFormData = { ...formData };
    let hasChanges = false;

    // 检查params中是否有与表单字段匹配的参数
    fields.forEach(field => {
      if (params[field.name] && params[field.name] !== formData[field.name]) {
        newFormData[field.name] = params[field.name];
        hasChanges = true;
      }
    });

    if (hasChanges) {
      setFormData(newFormData);
    }
  }, [params]);

  const handleChange = (field: string, value: string | Date) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
    // 清除该字段的错误
    if (errors[field]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };
  
  const showDatePicker = (fieldName: string) => {
    setDateTimePickerField(fieldName);
    setDatePickerVisible(true);
  };

  const hideDatePicker = () => {
    setDatePickerVisible(false);
    setDateTimePickerField(null);
  };

  const handleDateConfirm = (date: Date) => {
    if (dateTimePickerField) {
      handleChange(dateTimePickerField, date);
      hideDatePicker();
    }
  };

  const validateField = (field: FormField, value: any): string | null => {
    if (!field.rules) return null;

    for (const rule of field.rules) {
      if (rule.required && !value) {
        return rule.message || `${field.label}不能为空`;
      }
      if (rule.validator && typeof rule.validator === 'function') {
        const result = rule.validator(value);
        if (result === false) {
          return rule.message || `${field.label}验证失败`;
        }
        if (typeof result === 'string') {
          return result;
        }
      }
    }

    return null;
  };

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};
    let isValid = true;

    fields.forEach(field => {
      const error = validateField(field, formData[field.name]);
      if (error) {
        newErrors[field.name] = error;
        isValid = false;
      }
    });

    setErrors(newErrors);
    return isValid;
  };

  const handleSubmit = () => {
    if (validateForm()) {
      // 如果有图片字段，将图片数据合并到表单数据中
      const dataToSubmit = { ...formData };
      if (onImagesChange) {
        dataToSubmit.images = localImages;
      }
      onSubmit(dataToSubmit);
    }
  };

  const pickImage = async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== "granted") {
      Alert.alert("提示", "需要访问相册权限才能选择图片");
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    if (!result.canceled && result.assets[0].uri) {
      const newImages = [...localImages, result.assets[0].uri];
      setLocalImages(newImages);
      if (onImagesChange) {
        onImagesChange(newImages);
      }
    }
  };

  const takePhoto = async () => {
    const { status } = await ImagePicker.requestCameraPermissionsAsync();
    if (status !== "granted") {
      Alert.alert("提示", "需要相机权限才能拍照");
      return;
    }

    const result = await ImagePicker.launchCameraAsync({
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    if (!result.canceled && result.assets[0].uri) {
      const newImages = [...localImages, result.assets[0].uri];
      setLocalImages(newImages);
      if (onImagesChange) {
        onImagesChange(newImages);
      }
    }
  };

  const removeImage = (index: number) => {
    const newImages = localImages.filter((_, i) => i !== index);
    setLocalImages(newImages);
    if (onImagesChange) {
      onImagesChange(newImages);
    }
  };

  const renderField = (field: FormField) => {
    const commonInputProps = {
      style: styles.input,
      placeholder: field.placeholder || `请输入${field.label}`,
      value: formData[field.name] || '',
      onChangeText: (value: string) => handleChange(field.name, value)
    };

    const fieldContent = (() => {
      switch (field.type) {
        case 'select':
          return (
            <View style={styles.typeContainer}>
              {field.options?.map((option) => (
                <TouchableOpacity
                  key={option.value}
                  style={[
                    styles.typeButton,
                    formData[field.name] === option.value && styles.typeButtonActive
                  ]}
                  onPress={() => handleChange(field.name, option.value)}
                >
                  <Text style={[
                    styles.typeButtonText,
                    formData[field.name] === option.value && styles.typeButtonTextActive
                  ]}>{option.label}</Text>
                </TouchableOpacity>
              ))}
            </View>
          );
        case 'textarea':
          return (
            <TextInput
              {...commonInputProps}
              style={[styles.input, styles.textArea]}
              multiline
              numberOfLines={4}
            />
          );
        case 'phone':
          return (
            <TextInput
              {...commonInputProps}
              keyboardType="phone-pad"
            />
          );
        case 'number':
          return (
            <TextInput
              {...commonInputProps}
              keyboardType="numeric"
            />
          );
        case 'image':
          return (
            <View>
              <View style={styles.imageActions}>
                <TouchableOpacity style={styles.imageButton} onPress={pickImage}>
                  <Ionicons name="images" size={20} color={theme.colors.white} />
                  <Text style={styles.imageButtonText}>从相册选择</Text>
                </TouchableOpacity>
                <TouchableOpacity style={styles.imageButton} onPress={takePhoto}>
                  <Ionicons name="camera" size={20} color={theme.colors.white} />
                  <Text style={styles.imageButtonText}>拍照</Text>
                </TouchableOpacity>
              </View>
              {localImages.length > 0 && (
                <View style={styles.imagePreviewContainer}>
                  {localImages.map((uri, index) => (
                    <View key={index} style={styles.imagePreview}>
                      <Image source={{ uri }} style={styles.previewImage} />
                      <TouchableOpacity
                        style={styles.removeImageButton}
                        onPress={() => removeImage(index)}
                      >
                        <Ionicons
                          name="close-circle"
                          size={24}
                          color={theme.colors.status.pending}
                        />
                      </TouchableOpacity>
                    </View>
                  ))}
                </View>
              )}
            </View>
          );
        case 'datetime':
          const dateValue = formData[field.name] ? new Date(formData[field.name]) : null;
          const dateFormat = field.dateFormat || 'YYYY-MM-DD HH:mm';
          const displayValue = dateValue 
            ? dateValue.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
              })
            : '';
          return (
            <TouchableOpacity 
              style={styles.datePickerButton}
              onPress={() => showDatePicker(field.name)}
            >
              <View style={styles.datePickerContent}>
                <Text 
                  style={[styles.datePickerText, !displayValue && styles.datePickerPlaceholder]}
                >
                  {displayValue || field.placeholder || `请选择${field.label}`}
                </Text>
                <Ionicons name="calendar" size={20} color={theme.colors.text.secondary} />
              </View>
            </TouchableOpacity>
          );
        case 'location':
          // 在Web平台上使用普通文本输入而不是地图选择器
          if (Platform.OS === 'web') {
            return <TextInput {...commonInputProps} />;
          }
          return (
            <View>
              <View style={styles.locationInputContainer}>
                <TextInput
                  {...commonInputProps}
                  style={[styles.input, styles.locationInput]}
                  value={formData[field.name]}
                  editable={false}
                />
                <TouchableOpacity 
                  style={styles.mapButton}
                  onPress={() => {
                    router.push({
                      pathname: '/map-picker',
                      params: {
                        fieldName: field.name,
                        initialValue: formData[field.name]
                      }
                    });
                  }}
                >
                  <Ionicons name="map" size={20} color={theme.colors.white} />
                </TouchableOpacity>
              </View>
            </View>
          );
        default:
          return <TextInput {...commonInputProps} />;
      }
    })();

    const containerStyle = [
      styles.formGroup,
      field.width === 'half' && styles.halfWidth
    ];

    return (
      <View key={field.name} style={containerStyle}>
        <View style={styles.labelContainer}>
          <Text style={styles.label}>{field.label}</Text>
          {field.rules?.some(rule => rule.required) && (
            <Text style={styles.requiredMark}>*</Text>
          )}
        </View>
        {fieldContent}
        {errors[field.name] && (
          <Text style={styles.errorText}>{errors[field.name]}</Text>
        )}
      </View>
    );
  };

  return (
    <View style={styles.formContainer}>
      {fields.map(renderField)}
      <TouchableOpacity style={styles.submitButton} onPress={handleSubmit}>
        <Text style={styles.submitButtonText}>{submitText}</Text>
      </TouchableOpacity>
      
      <DateTimePickerModal
        isVisible={isDatePickerVisible}
        mode="datetime"
        onConfirm={handleDateConfirm}
        onCancel={hideDatePicker}
        confirmTextIOS="确认"
        cancelTextIOS="取消"
        headerTextIOS="选择日期和时间"
        locale="zh_CN"
      />
    </View>
  );
}

const styles = StyleSheet.create({
  formContainer: {
    padding: 16,
  },
  formGroup: {
    marginBottom: 16,
  },
  halfWidth: {
    width: '48%',
  },
  labelContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  label: {
    fontSize: 16,
    fontWeight: '500',
    color: theme.colors.text.primary,
  },
  requiredMark: {
    color: '#ff4d4f',
    marginLeft: 4,
    fontSize: 14,
  },
  input: {
    backgroundColor: theme.colors.white,
    borderWidth: 1,
    borderColor: theme.colors.border.default,
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    color: theme.colors.text.primary,
  },
  textArea: {
    height: 100,
    textAlignVertical: 'top',
  },
  typeContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginTop: 8,
  },
  typeButton: {
    backgroundColor: theme.colors.white,
    borderWidth: 1,
    borderColor: theme.colors.border.default,
    borderRadius: 20,
    paddingVertical: 8,
    paddingHorizontal: 16,
    marginRight: 10,
    marginBottom: 10,
  },
  typeButtonActive: {
    backgroundColor: theme.colors.primary,
    borderColor: theme.colors.primary,
  },
  typeButtonText: {
    color: theme.colors.text.primary,
  },
  typeButtonTextActive: {
    color: theme.colors.white,
  },
  submitButton: {
    backgroundColor: theme.colors.primary,
    borderRadius: 8,
    padding: 16,
    alignItems: 'center',
    marginTop: 16,
  },
  submitButtonText: {
    color: theme.colors.white,
    fontSize: 16,
    fontWeight: '600',
  },
  errorText: {
    color: '#ff4d4f',
    fontSize: 12,
    marginTop: 4,
  },
  imageActions: {
    flexDirection: "row",
    gap: 12,
    marginTop: 8,
  },
  imageButton: {
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: theme.colors.primary,
    borderRadius: 8,
    paddingVertical: 8,
    paddingHorizontal: 12,
    gap: 6,
  },
  imageButtonText: {
    color: theme.colors.white,
    fontSize: 14,
    fontWeight: "500",
  },
  imagePreviewContainer: {
    flexDirection: "row",
    flexWrap: "wrap",
    gap: 8,
    marginTop: 12,
  },
  imagePreview: {
    width: 100,
    height: 100,
    borderRadius: 8,
    overflow: "hidden",
    position: "relative",
  },
  previewImage: {
    width: "100%",
    height: "100%",
  },
  removeImageButton: {
    position: "absolute",
    top: -6,
    right: -6,
    backgroundColor: theme.colors.white,
    borderRadius: 12,
  },
  datePickerButton: {
    backgroundColor: theme.colors.white,
    borderWidth: 1,
    borderColor: theme.colors.border.default,
    borderRadius: 8,
    padding: 12,
  },
  datePickerContent: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  datePickerText: {
    fontSize: 16,
    color: theme.colors.text.primary,
  },
  datePickerPlaceholder: {
    color: theme.colors.text.tertiary,
  },
  locationInputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  locationInput: {
    flex: 1,
    borderTopRightRadius: 0,
    borderBottomRightRadius: 0,
  },
  mapButton: {
    backgroundColor: theme.colors.primary,
    borderTopRightRadius: 8,
    borderBottomRightRadius: 8,
    padding: 12,
    justifyContent: 'center',
    alignItems: 'center',
  },
});